<?php

namespace Common\Logic;

/**
 * 微信用户logic
 */
class WxUserLogic extends BaseLogic
{
    const USER_COOKIE_NAME = 'user_info20190730';
    const USER_FIELD = 'id,openid,photo,name,sex,phone,user_state,prov,city,birthday';
    const CRYPT_KEY = 'FmL2UrsftJeF7LecaBh0V7UZHiQ7VsDN';

    private $userModel;

    public function __construct()
    {
        parent::__construct();
        $this->userModel = D('User');
    }

    /**
     * 获取用户登录信息
     * @return mixed
     */
    public function getUserInfo()
    {
        $userInfoRes = $this->getUserInfoByCookie();
        if (!static::$res->isSuc($userInfoRes)) {
            return static::$res->err("用户未登陆");
        }
        $userInfo = $userInfoRes['Result'];

        if ($userInfo['expire'] < time()) {
            return static::$res->err("登陆信息已过期");
        }

        $openId = $userInfo['openid'];
        $id = $userInfo['id'];

        $userWhere = array(
            "openid" => $openId,
            "id" => $id,
            "user_state" => array('neq', -1)
        );

        if ($this->userModel->where($userWhere)->count() < 1) {
            return static::$res->err("登陆信息异常");
        }

        $userInfo['expire'] = strtotime("+1 day");

        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 通过id获取用户信息
     * @param string $id
     * @param string $openId
     * @return mixed
     */
    public function getUserInfoById($id = '', $openId = '')
    {
        if (empty($id) && empty($openId)) {
            return static::$res->err("id不能为空");
        }
        $userWhere = array(
            "user_state" => array('neq', -1)
        );
        if (!empty($id)) {
            $userWhere['id'] = $id;
        }
        if (!empty($openId)) {
            $userWhere['openid'] = $openId;
        }

        $userInfo = $this->userModel->where($userWhere)->field(static::USER_FIELD)->find();
        if (empty($userInfo)) {
            return static::$res->err("用户未注册");
        }

        $userInfo['expire'] = strtotime("+1 day");
        $this->setUserInfoToCookie($userInfo);
        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 添加用户信息返回用户信息
     * @param $userInfo
     * @return mixed
     */
    public function addUser($userInfo)
    {
        static $fields = array(
            "openid" => array("empty" => "openId不能为空"),
            "photo" => array(),
            "name" => array("empty" => "用户名不能为空"),
            "sex" => array(),
            "phone" => array(),
            "parent_id" => array(),
        );

        $data = array();
        foreach ($fields as $title => $vo) {
            $val = $userInfo[$title];
            if (!empty($vo['empty'])) {
                if (empty($val)) {
                    return static::$res->err($vo['empty']);
                }
            }
            $data[$title] = $val; 
        }

        //获取是否注册
        $userInfoRes = $this->getUserInfoById("", $data['openid']);
        if (static::$res->isSuc($userInfoRes)) {
            return $userInfoRes;
        }

        if (empty($data["sex"])) {
            $data["sex"] = 3;
        }
        if (empty($data["parent_id"])) {
            $data["parent_id"] = 0;
        }
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['user_state'] = 1;

        $id = $this->userModel->add($data);
        if (empty($id)) {
            return static::$res->err("数据库异常，添加失败");
        }

        //添加成功，返回用户信息
        return $this->getUserInfoById("", $data['openid']);
    }

    /**
     * 更新数据
     * @param string $id
     * @param string $openId
     * @param $param
     * @return mixed
     */
    public function updateUser($id = '', $openId = '', $param = array())
    {
        if (empty($id) && empty($openId)) {
            return static::$res->err("id不能为空");
        }
        $userWhere = array();
        if (!empty($id)) {
            $userWhere['id'] = $id;
        }
        if (!empty($openId)) {
            $userWhere['openid'] = $openId;
        }

        unset($param['id']);
        unset($param['openid']);
        unset($param['add_time']);
        unset($param['user_state']);

        if (empty($param)) {
            return static::$res->err("没有任何改变");
        }

        $count = $this->userModel->where($userWhere)->save($param);
        if (empty($count)) {
            return static::$res->err("用户没有改变");
        }

        //添加成功，返回新用户信息
        return $this->getUserInfoById($id, $openId);
    }

    /**
     * 通过cookie获取登录信息
     * @return mixed
     */
    private function getUserInfoByCookie()
    {
        $cookieStr = cookie(static::USER_COOKIE_NAME);

        if (empty($cookieStr) && APP_STATUS == "zyloc") {
            return $this->getUserInfoById(4);
        }

        if (empty($cookieStr)) {
            return static::$res->err("登录信息不存在");
        }
        $userInfoJson = \Think\Crypt::decrypt($cookieStr, static::CRYPT_KEY);
        $userInfo = json_decode($userInfoJson, true);
        if (empty($userInfo)) {
            return static::$res->err("登录信息失效");
        }

        return static::$res->suc('成功', $userInfo);
    }

    /**
     * 将用户信息写入到cookie
     * @param type $userInfo
     */
    private function setUserInfoToCookie($userInfo)
    {
        $userInfoJson = json_encode($userInfo);
        $val = \Think\Crypt::encrypt($userInfoJson, static::CRYPT_KEY);
        cookie(static::USER_COOKIE_NAME, $val);
    }
}
